# Importing Data
USA <- read_excel("C:/Users/Biniam/Desktop/Documents/Academic/Thesis/Analysis Folder/Excel Files/Bahrain/USA.xlsx")

# Checking the Imported Data
View(USA)

# Creating Time Series Data
USA_ts <- ts(USA, start=c(2005,01), end=c(2019,07), frequency=12)

# Viewing and Checking the Created Time Series Data
USA_ts
sum(is.na(USA_ts))
library(forecast)
USA_ts <- tsclean(USA_ts)

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(USA_ts)
plot(aggregate(USA_ts,FUN=mean))

# Decomposing
USA_ts_decomp <- decompose(USA_ts)
plot(USA_ts_decomp)

# Testing for Stationarity
acf(USA_ts, lag.max=20)
pacf(USA_ts, lag.max=20)

# To see any seasonal effect
boxplot(USA_ts~cycle(USA_ts))

# To remove trend effect
USA_ts_diff <- diff(USA_ts)
plot(USA_ts_diff)

# To remove variance effect
USA_ts_log <- log(USA_ts)
plot(USA_ts_log)

# To remove both (Trend and Variance) effects
USA_ts_both <- diff(log(USA_ts))
plot(USA_ts_both)


# Dealing with ACF and PACF
install.packages("tseries")
library(tseries)
acf(USA_ts, lag.max=20)
acf(log(USA_ts), lag.max=20)
acf(diff(USA_ts), lag.max=20)
acf(diff(log(USA_ts)), lag.max=20)
pacf(USA_ts, lag.max=20)
pacf(log(USA_ts), lag.max=20)
pacf(diff(USA_ts), lag.max=20)
pacf(diff(log(USA_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
USA_ts_model <- auto.arima(USA_ts)
USA_ts_model
USA_ts_model <- auto.arima(USA_ts, ic="aic", trace = TRUE)
USA_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(USA_ts_model$resid)
acf(USA_ts_model$residuals, main='ACF Residual')
pacf(USA_ts_model$residuals, main='ACF Residual')
Box.test(USA_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
library(forecast)
USA_ts_forecast <- forecast (USA_ts_model, level=c(95), h=257)
plot(USA_ts_forecast)
USA_ts_forecast             

write.table(USA_ts_forecast, file="USA_TSA.csv", sep=",")
